# import requests
# import json
#
# # 企业微信机器人的Webhook地址
# webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bd5c0bc6-ff20-4335-8b7e-edab91c6dcd8"
#
# # 构建图文消息的内容
# message = {
#     "msgtype": "image",
#     "image": {
#         "base64": "BASE64_ENCODED_IMAGE_DATA",
#         "md5": "IMAGE_MD5_HASH"
#     }
# }
#
#
# # 发送POST请求
# response = requests.post(webhook_url, data=json.dumps(message), headers={'Content-Type': 'application/json'})
#
# # 打印响应结果
# print(response.text)

# import requests
# import hashlib
# import base64
#
# # 企业微信机器人的Webhook地址
# webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bd5c0bc6-ff20-4335-8b7e-edab91c6dcd8"
#
# # 图片文件路径
# image_path = rf"E:\py图片下载\dataimg\5.png"
#
# # 读取图片文件并计算MD5哈希值
# with open(image_path, "rb") as image_file:
#     image_data = image_file.read()
#     image_md5 = hashlib.md5(image_data).hexdigest()
#
# # 将图片数据转换为Base64编码
# image_base64 = base64.b64encode(image_data).decode("utf-8")
#
# # 构建消息内容
# message = {
#     "msgtype": "image",
#     "image": {
#         "base64": image_base64,
#         "md5": image_md5
#     }
# }
#
# # 发送POST请求
# response = requests.post(webhook_url, json=message)
#
# # 打印响应结果
# print(response.text)


# import requests
# import hashlib
# import base64
#
# # 企业微信机器人的Webhook地址
# webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bd5c0bc6-ff20-4335-8b7e-edab91c6dcd8"
#
# # 图片文件路径
# image_path = rf"E:\py图片下载\dataimg\5.png"
#
# # 读取图片文件并计算MD5哈希值
# with open(image_path, "rb") as image_file:
#     image_data = image_file.read()
#     image_md5 = hashlib.md5(image_data).hexdigest()
#
# # 将图片数据转换为Base64编码
# image_base64 = base64.b64encode(image_data).decode("utf-8")
#
# # 构建图片消息内容
# image_message = {
#     "msgtype": "image",
#     "image": {
#         "base64": image_base64,
#         "md5": image_md5
#     }
# }
#
# # 构建文字消息内容
# text_message = {
#     "msgtype": "text",
#     "text": {
#         "content": "这是自动发送的文字消息"
#     }
# }
#
# # 发送文字消息
# text_response = requests.post(webhook_url, json=text_message)
# print("文字消息发送结果:", text_response.text)
# # 发送图片消息
# image_response = requests.post(webhook_url, json=image_message)
# print("图片消息发送结果:", image_response.text)


# import requests

#
# # 示例用法
# if __name__ == "__main__":
#     webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bd5c0bc6-ff20-4335-8b7e-edab91c6dcd8"
#     image_path = rf"E:\py图片下载\dataimg\5.png"
#     text_content = "这是自动发送的文字消息"
#
#     send_wechat_message(webhook_url, image_path=image_path, text_content=text_content)


# from flask import Flask, request, jsonify
# from flask_cors import CORS
# import requests
# import hashlib
# import base64
# import schedule
# import time
# from datetime import datetime
# import json
#
# app = Flask(__name__)
# CORS(app)
#
# def send_wechat_message(webhook_url, image_path=None, text_content=None):
#     """
#     发送企业微信消息（文字和图片）
#
#     :param webhook_url: 企业微信机器人的Webhook地址
#     :param image_path: 图片文件路径（可选）
#     :param text_content: 文字消息内容（可选）
#     """
#     if not webhook_url:
#         raise ValueError("Webhook URL不能为空")
#
#     messages = []
#
#     if image_path:
#         with open(image_path, "rb") as image_file:
#             image_data = image_file.read()
#             image_md5 = hashlib.md5(image_data).hexdigest()
#             image_base64 = base64.b64encode(image_data).decode("utf-8")
#
#         image_message = {
#             "msgtype": "image",
#             "image": {
#                 "base64": image_base64,
#                 "md5": image_md5
#             }
#         }
#         messages.append(image_message)
#
#     if text_content:
#         text_message = {
#             "msgtype": "text",
#             "text": {
#                 "content": text_content
#             }
#         }
#         messages.append(text_message)
#
#     for message in messages:
#         response = requests.post(webhook_url, json=message)
#         print(f"{message['msgtype']}消息发送结果:", response.text)
#
# def schedule_message(webhook_url, image_path=None, text_content=None, time_str=None):
#     """
#     安排定时发送企业微信消息
#
#     :param webhook_url: 企业微信机器人的Webhook地址
#     :param image_path: 图片文件路径（可选）
#     :param text_content: 文字消息内容（可选）
#     :param time_str: 定时发送的时间字符串，格式为 "HH:MM"
#     """
#     if time_str:
#         try:
#             schedule_time = datetime.strptime(time_str, "%H:%M").time()
#             schedule.every().day.at(schedule_time.strftime("%H:%M")).do(send_wechat_message, webhook_url, image_path=image_path, text_content=text_content)
#         except ValueError:
#             return "无效的时间格式，请使用 'HH:MM' 格式", 400
#     else:
#         return "请提供定时发送的时间", 400
#
# @app.route('/schedulehomet', methods=['POST'])
# def schedule_message_api():
#     # return '测试'
#     # data = request.get_json()
#     print('来了',request.json)
#     webhook_url = request.json.get('webhook_url')
#     image_path = request.json.get('image_path')
#     text_content = request.json.get('text_content')
#     time_str = request.json.get('time_str')
#     result, status_code = schedule_message(webhook_url, image_path=image_path, text_content=text_content, time_str=time_str)
#     return result, status_code
#
# if __name__ == '__main__':
#     app.run(host='0.0.0.0', port=7010)
from flask import Flask, request, jsonify
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from werkzeug.utils import secure_filename
import os
import requests
from flask_cors import CORS
import hashlib
import base64
import json
from datetime import datetime

from setMysql import *
app = Flask(__name__)
# 配置CORS，允许来自任何来源的请求
CORS(app)
scheduler = BackgroundScheduler()
scheduler.start()
# 上传目录
UPLOAD_FOLDER="uploads"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# 允许上传的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

image_path = ""
imagesName = None
# 微信机器人api
webhook_url = None
#
def send_wechat_message( image_path=None, text_content=None):
    """
    发送企业微信消息（文字和图片）

    :param webhook_url: 企业微信机器人的Webhook地址
    :param image_path: 图片文件路径（可选）
    :param text_content: 文字消息内容（可选）
    """
    if not webhook_url:
        raise ValueError("Webhook URL不能为空")

    messages = []

    if imagesName:
        with open(image_path, "rb") as image_file:
            image_data = image_file.read()
            image_md5 = hashlib.md5(image_data).hexdigest()
            image_base64 = base64.b64encode(image_data).decode("utf-8")

        image_message = {
            "msgtype": "image",
            "image": {
                "base64": image_base64,
                "md5": image_md5
            }
        }
        messages.append(image_message)

    if text_content:
        text_message = {
            "msgtype": "text",
            "text": {
                "content": text_content
            }
        }
        messages.append(text_message)

    for message in messages:
        response = requests.post(webhook_url, json=message)
        print(f"{message['msgtype']}消息发送结果:", response.text)
        # if message.msgtype == "text":
        #     if json.loads(response.text)['errmsg'] == 'ok':
    code = updataMysql(text_content)
    if code == 1:
        print('修改成功')





def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS



def setImages(img):
    global image_path
    image_path = rf"D:\youxi\企业微信消息\uploads\{img}"
    # image_path = rf"/home/wx/api/uploads/{img}"

@app.route('/schedule_message', methods=['POST'])
def schedule_message():
    global imagesName,webhook_url
    data = request.get_json()
    send_time = data.get('send_time')
    message = data.get('message')
    try:
        webhook_url = data.get('webhook_url')
    except:
        return jsonify({'message': '设置失败,未添加微信机器人api', 'status': 2}), 200
    try:
        imagesName = data.get('imageName')
        if imagesName:
            setImages(imagesName)
    except:
        imagesName = None
        pass
    resultDate = data.get('send_data')
    print(message,imagesName,image_path)
    # 假设你有一个字符串格式的时间
    send_time_out = rf'{resultDate} {send_time}'
    # 定义时间字符串的格式
    format_string = "%Y-%m-%d %H:%M:%S"

    # 使用strptime函数将字符串转换为datetime对象
    datetime_obj = datetime.strptime(send_time_out, format_string)

    # 打印转换后的datetime对象
    print(datetime_obj)
    if not send_time or not message:
        return 'Missing send_time or message', 400
    try:
        # 获取当前日期和时间
        now = datetime.now()
        # # 格式化日期和时间
        formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
        # 生成一个唯一的任务ID，这里简单使用当前时间戳
        job_id = str(int(datetime.now().timestamp()))
        scheduler.add_job(send_request, 'date', run_date=datetime_obj, args=[message],id=job_id)
        code = mysqlUpdata((webhook_url,imagesName,message,datetime_obj,job_id,formatted_time))
        if code == 1:
            return jsonify({'message':'时间设定为 {}'.format(datetime_obj),'status': 1}), 200
        else:
            return jsonify({'message': '设置失败', 'status': 2}), 200
    except:
        return jsonify({'message': '设置失败', 'status': 2}), 200

def send_request(message):
    global image_path, webhook_url
    # url = 'http://example.com/send_message'  # 替换为实际的请求URL
    # data = {'message': message}
    # response = requests.post(url, json=data)
    # print('Message sent:', response.text)
    # 企业微信机器人的Webhook地址
    # webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bd5c0bc6-ff20-4335-8b7e-edab91c6dcd8"

    text_content = message

    send_wechat_message(image_path=image_path, text_content=text_content)

@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求中是否包含文件部分
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']

    # 如果用户没有选择文件，浏览器也会提交一个空的文件名
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    # 检查文件扩展名是否允许
    if not allowed_file(file.filename):
        return jsonify({'error': 'Invalid file extension'}), 400

    # 确保文件名安全
    filename = secure_filename(file.filename)

    # 保存文件到指定目录
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    try:
        return jsonify({'message': '图片上传成功','status': 1}), 200
    except:
        return jsonify({'message': '图片上传失败', 'status': 2}), 200

# 时间日期转换
def Timeoutday(send_time_out):
    # 定义时间字符串的格式
    format_string = "%Y-%m-%d %H:%M:%S"

    # 使用strptime函数将字符串转换为datetime对象
    datetime_obj = datetime.strptime(send_time_out, format_string)

    print(datetime_obj)
    return datetime_obj


# 获取任务列表
@app.route('/uploadtaskList', methods=['POST'])
def uploadtaskList():
    data = request.get_json()
    webhookurlkey = data.get('webhook_url')
    code = SelectaskList(webhookurlkey)
    if code != 2:
        _arr = []
        for key in code:
            formatted_time = key[4].strftime('%Y-%m-%d %H:%M:%S')
            formatted_time_create = key[7].strftime('%Y-%m-%d %H:%M:%S')
            __arraybey = {
                "webhookurl" : key[1],
                "imagepath": key[2],
                "message": key[3],
                "resultDate": formatted_time,
                "id": key[0],
                "job_id": key[6],
                "createTime": formatted_time_create,
                "status": key[5]
            }
            _arr.append(__arraybey)
        return jsonify({'message': '获取成功','list': _arr, 'status': 1}), 200
    else:
        return jsonify({'message': '获取失败', 'list':[], 'status': 2}), 200

# 取消定时任务
@app.route('/cancel_schedule', methods=['POST'])
def cancel_schedule():
    data = request.get_json()
    job_id = data.get('job_id')
    if not job_id:
        return jsonify({'message': 'Missing job ID', 'status': 2}), 400
    try:
        scheduler.remove_job(job_id)
        # 修改数据库
        _code = updataMysqlcalsh(job_id)
        if _code == 1:
            return jsonify({'message': '任务取消成功', 'status': 1}), 200
        else:
            return jsonify({'message': 'Missing job ID', 'status': 2}), 400
    except Exception as e:
        return jsonify({'message': f'取消任务时出错: {str(e)}', 'status': 2}), 500

if __name__ == '__main__':
    # 创建上传目录
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(host='0.0.0.0',port=8000,debug=True)




